import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCustomerStore } from '@/stores/customerStore'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/admin',
    component: () => import('@/layouts/AdminLayout.vue'),
    children: [
      {
        path: '',
        redirect: '/admin/dashboard'
      },
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('@/views/admin/Dashboard.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('@/views/admin/UserManagement.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
      },
      {
        path: 'products',
        name: 'ProductManagement',
        component: () => import('@/views/admin/ProductManagement.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
      },
      {
        path: 'orders',
        name: 'OrderManagement',
        component: () => import('@/views/admin/OrderManagement.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
      },
      {
        path: 'delivery',
        name: 'DeliveryManagement',
        component: () => import('@/views/admin/DeliveryManagement.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
      },
      {
        path: 'profile',
        name: 'AdminProfile',
        component: () => import('@/views/admin/Profile.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
      }
    ]
  },
  {
    path: '/customer',
    component: () => import('@/layouts/CustomerLayout.vue'),
    children: [
      {
        path: '',  // 空路径，访问 /customer 时重定向到 products
        redirect: '/customer/products'
      },
      {
        path: 'dashboard',  // 访问 /customer/dashboard 时重定向到 products
        redirect: '/customer/products'
      },
      {
        path: 'products',
        name: 'CustomerProducts',
        component: () => import('@/views/products/ProductList.vue'),
        meta: { requiresAuth: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 修改路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const customerStore = useCustomerStore()
  
  // 初始化 store
  await Promise.all([
    userStore.initialize(),
    customerStore.initialize()
  ])

  if (to.meta.requiresAuth) {
    // 检查是否已登录（系统用户或客户）
    if (userStore.isLoggedIn || customerStore.isLoggedIn) {
      // 检查是否需要管理员权限
      if (to.meta.requiresAdmin && userStore.user?.role !== 'admin') {
        next('/login')
      } else {
        next()
      }
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router